package com.youbo.common.utils;

import org.apache.http.util.TextUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * @author: macy
 * @Email: 420534221@qq.com
 * @Date: 2020/12/16
 * @describe:
 */
public class Base64Tools {

    /**
     *
     * @param arta
     */
    public static void main(String[] arta)throws  Exception{
        System.out.println(genHMAC("utj77obgueh3a5jx0olx&1608087415&cYqippRZdx","476d57ce065040de96798ffbff361a44"));
    }

    /**
     *HMACSHA1 data
     *Base64
     * @param data 原文
     * @param key   密匙
     * @return   加密后的字符串
     */

    public static String genHMAC(String data, String key) {
        String string= null;
        try {
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes("utf-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signinKey);
            byte[] rawHmac = mac.doFinal(data.getBytes("utf-8"));
            return Base64.getEncoder().encodeToString(rawHmac);
            //string=new String(Base64.getEncoder().encode(rawHmac));
            //string=new String(encode(rawHmac));
        } catch (Exception e) {}
        return string;
    }




    /**
     * 功能：编码byte[]
     *
     * @author jiangshuai
     * @date 2016年10月03日
     * @param data
     *            源
     * @return char[]
     */
    public static char[] encode(byte[] data) {
        char[] out = new char[((data.length + 2) / 3) * 4];
        for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
            boolean quad = false;
            boolean trip = false;

            int val = (0xFF & (int) data[i]);
            val <<= 8;
            if ((i + 1) < data.length) {
                val |= (0xFF & (int) data[i + 1]);
                trip = true;
            }
            val <<= 8;
            if ((i + 2) < data.length) {
                val |= (0xFF & (int) data[i + 2]);
                quad = true;
            }
            out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 1] = alphabet[val & 0x3F];
            val >>= 6;
            out[index + 0] = alphabet[val & 0x3F];
        }
        return out;
    }

    private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
            .toCharArray();
}
